import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useModel } from '@umijs/max';
import styles from './CenterL.less';
import * as d3 from 'd3';

// 定义数据项的类型
interface ScoreData {
  year: string;
  province: string;
  campus: string;
  category: string;
  category2: string;
  proname: string;
  max: string;
  min: string;
  average: string;
}

// 平均分数据项类型
interface AverageScore {
  province: string;
  year: string;
  average: number;
}

const CenterL: React.FC = () => {
  const { scoreData } = useModel('global');

  // 提取所有省份
  const provinces = useMemo(() => {
    const provinceSet = new Set<string>();
    scoreData.forEach(item => provinceSet.add(item.province));
    return Array.from(provinceSet);
  }, [scoreData]);

  // 根据省份和年份计算每个省份每年的平均分
  const averageScores = useMemo(() => {
    const provinceYearMap: { [province: string]: { [year: string]: number[] } } = {};

    // 将数据根据省份和年份进行分组
    scoreData.forEach(item => {
      const { year, province, average } = item;
      if (!provinceYearMap[province]) {
        provinceYearMap[province] = {};
      }
      if (!provinceYearMap[province][year]) {
        provinceYearMap[province][year] = [];
      }
      provinceYearMap[province][year].push(Number(average));
    });

    // 计算每个省份每年的平均分
    const averages: AverageScore[] = [];
    for (const province in provinceYearMap) {
      for (const year in provinceYearMap[province]) {
        const scores = provinceYearMap[province][year];
        const avgScore = d3.mean(scores) || 0; // 计算平均分，确保不是 NaN
        averages.push({ province, year, average: avgScore });
      }
    }

    return averages;
  }, [scoreData]);

  // 绘制折线图
  const svgRef = useRef<SVGSVGElement | null>(null);

  // 创建 Tooltip 引用
  const tooltipRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!svgRef.current || averageScores.length === 0 || !tooltipRef.current) return;

    const margin = { top: 40, right: 40, bottom: 100, left: 20 };
    const width = 620 - margin.left - margin.right;
    const height = 500 - margin.top - margin.bottom;

    const svg = d3.select(svgRef.current)
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .append('g')
      .attr('transform', `translate(${margin.left},${margin.top})`);

    // 创建横坐标（年份）比例尺
    const x = d3.scaleBand()
      .domain(averageScores.map(d => d.year))  // 横坐标是年份
      .range([0, width])
      .padding(0.1);

    // 创建纵坐标（平均分）比例尺
    const y = d3.scaleLinear()
      .domain([d3.min(averageScores, (dataPoint: { average: any; }) => dataPoint.average) || 0, d3.max(averageScores, (dataPoint: { average: any; }) => dataPoint.average) || 100])
      .nice()
      .range([height, 0]);

    // 创建颜色比例尺
    const color = d3.scaleOrdinal(d3.schemeCategory10);

    // 绘制横坐标轴
    svg.append('g')
      .attr('transform', `translate(0,${height})`)
      .call(d3.axisBottom(x))
      .selectAll('text')
      .attr('transform', 'rotate(-45)')
      .style('text-anchor', 'end');

    // 绘制纵坐标轴
    svg.append('g')
      .call(d3.axisLeft(y));

    // 按照省份分组数据
    const provincesData = d3.group(averageScores, (dataPoint: AverageScore) => dataPoint.province);

    // 绘制每条折线
    provincesData.forEach((provinceData: any, province: any) => {
      const line = d3.line()
        .x((d: AverageScore) => x(d.year) + x.bandwidth() / 2)
        .y((d: AverageScore) => y(d.average))
        .curve(d3.curveCatmullRom);  // 使用平滑曲线

      svg.append('path')
        .data([provinceData])  // 使用数据
        .attr('class', 'line')
        .attr('d', line)  // 绘制路径
        .style('fill', 'none')
        .style('stroke', color(province))  // 使用不同颜色区分省份
        .style('stroke-width', 3)
        .style('stroke-linejoin', 'round') // 圆角连接点
        .style('filter', 'url(#drop-shadow)'); // 添加阴影效果

      // 添加每个数据点的圆圈
      svg.selectAll(`.dot-${province}`)
        .data(provinceData)
        .enter().append('circle')
        .attr('class', `dot-${province}`)
        .attr('cx', (d: AverageScore) => x(d.year) + x.bandwidth() / 2)
        .attr('cy', (d: AverageScore) => y(d.average))
        .attr('r', 6)  // 增加圆圈的大小
        .style('fill', color(province))
        .style('stroke', '#fff')
        .style('stroke-width', 2)
        .on('mouseover', function (event: { pageX: number; pageY: number; }, d: AverageScore) {
          // 显示 Tooltip
          tooltipRef.current!.style.display = 'block';
          tooltipRef.current!.style.left = `${event.pageX + 10}px`;
          tooltipRef.current!.style.top = `${event.pageY + 10}px`;
          tooltipRef.current!.innerHTML = `${d.province} - ${d.year}年: 平均分 ${d.average}`;
        })
        .on('mouseout', function () {
          // 隐藏 Tooltip
          tooltipRef.current!.style.display = 'none';
        });
    });

    // 添加阴影效果
    svg.append('defs')
      .append('filter')
      .attr('id', 'drop-shadow')
      .append('feDropShadow')
      .attr('dx', 2)
      .attr('dy', 2)
      .attr('stdDeviation', 3)
      .attr('flood-color', 'rgba(0, 0, 0, 0.3)');
  }, [averageScores]);

  return (
    <div className={styles.container}>
      <div className={styles.title}>
        各省每年录取平均分变化趋势
      </div>

      <div className={styles.chart}>
        <svg ref={svgRef}></svg>
      </div>

      {/* Tooltip */}
      <div
        ref={tooltipRef}
        style={{
          position: 'absolute',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          color: 'white',
          padding: '0',
          borderRadius: '4px',
          display: 'none',
          pointerEvents: 'none',
          fontSize: '12px',
          zIndex: 1000,
        }}
      >
        {/* Tooltip 内容会在鼠标悬停时动态填充 */}
      </div>
    </div>
  );
};

export default CenterL;
